import type { HttpStatusCodeValueType } from './constant';
import environment from './environment'; // 环境，服务配置文件
import { useUserStore } from '@/store/modules/user';
import { getToken } from '@/utils/token';

const baseUrl = environment.envConfigs.url;

export interface requestType<T> {
	data?: T;
	message: string | null;
	statusCode: HttpStatusCodeValueType;
	pagination?: {
		page: number;
		size: number;
		total: number;
	};
}
// type ServeType = 'AUTH' | 'PROPERTY' | 'FILE' | 'JOB' | 'BPM'

type HttpMethod = 'POST' | 'OPTIONS' | 'GET' | 'HEAD' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';

const DEFAULT_METHOD: HttpMethod = 'GET';

interface Request {
	url: string;
	method: HttpMethod;
	body?: any;
	hideLoading?: boolean;
	withCredentials?: boolean;
	headers?: any;
	timeout?: number;
}
async function request<T>({
	url = '',
	method = DEFAULT_METHOD,
	body = {},
	hideLoading = true, //是否显示请求loading
	withCredentials = true,
	headers = {},
	timeout = 6000
}: Request): Promise<requestType<T>> {
	if (!hideLoading) {
		uni.showLoading({
			mask: true
		});
	}
	url = baseUrl + url;
	const token = getToken();
	const authHeaders: any = {};
	if (token) {
		authHeaders.Authorization = token ? `Bearer ${token}` : '';
	}
	try {
		const res: any = await uni.request({
			url,
			method: method,
			data: body,
			header: Object.assign(authHeaders, headers),
			withCredentials,
			timeout,
			enableCache: true // 自动处理缓存
		});

		const { data }: any = res;
		if (data.statusCode === 606) {
			//需要重新登录清除store
			useUserStore().$reset();
			uni.reLaunch({
				url: ''
			});
			return Promise.reject('需要重新登录');
		}

		//      if (data.statusCode === 401) {
		// uni.redirectTo({
		//   url: '/pages/login/login' // 关闭当前页面，跳转到对应路径的页面
		// })
		//          return Promise.reject()
		//      }

		if (data.statusCode === 200) {
			return Promise.resolve(data);
		}

		if (data.statusCode === 404) {
			return Promise.reject(data);
		}
		uni.showToast({
			icon: 'none',
			title: data.message || ''
		});
		//异常抛出
		return Promise.reject(data);
	} catch (error) {
		return Promise.reject('请求失败');
	} finally {
		if (!hideLoading) {
			uni.hideLoading();
		}
	}
}
export default request;
